<template lang="html">
    <div class="dashboard-page" v-loading="loading.status" :element-loading-text="loading.txt" v-loading.fullscreen.lock="loading.full">
    </div>
</template>
<script>
// import NProgress from 'nprogress'
// import 'nprogress/nprogress.css'
import store from '../../store/index.js';
import router from '../../router'
import Global from '../../tools/global';
import routeConfig from '../../tools/route-config';

export default {
    data() {
        return {
            loading: {
                status: true,
                txt: '正在验证...',
                full: true,
            },
            itemName: '',
            allRoutes: null,
            routeData: [],
            historyBack: null
        }
    },
    created() {
        this.getIsSchool();
        this.getIsCheckLevel()
        this.getTitle();
        this.checkToken();

    },
    mounted() {
        this.allRoutes = deep_clone(router.options.routes);

        //防止页面后退
        this.historyBack = () => {
            history.pushState(null, null, document.URL);
            window.addEventListener('popstate', function() {
                history.pushState(null, null, document.URL);
            });
        }

    },
    destroyed() {
        this.historyBack = null
    },
    methods: {
        /**
         * 登陆后获取 title
         * @return {[type]} [description]
         */
        getTitle() {
            let success = (data => {
                if (!is_empty(data.data)) {
                    sessionStorage.setItem('siteTitle', data.data.name);
                    sessionStorage.setItem('siteIcon', (this.BASE_URL + data.data.path));
                    document.title = data.data.name;

                    let link = document.querySelector("link[rel*='icon']") || document.createElement('link');
                    link.type = 'image/x-icon';
                    link.rel = 'shortcut icon';
                    link.href = this.BASE_URL + data.data.path;
                    document.getElementsByTagName('head')[0].appendChild(link);
                }
            });
            let fail = (data => {
                this.$message.error(data.msg);
            })

            this.$ajax.get('api/setting/browser_set', { params: {}, func: { success: success, fail: fail } })
        },
        checkToken() {
            this.loading.status = true;
            // NProgress.start() // 开启Progress
            // 重写成功回调
            let success = (data => {
                this.routeData = data.data.personal;
                this.loading.txt = '验证成功...';
                this.loading.status = false;
                this.filterRoutes();
              
                sessionStorage.setItem("user_info_str", JSON.stringify(deep_clone(data.data.userinfo)))
                sessionStorage.setItem("manage_url", sessionStorage.getItem('/admin'))
                sessionStorage.setItem("ItcJwtToken", data.data.userinfo.ItcJwtToken)
                store.commit('SET_USERINFO', data.data.userinfo);
                Global.user_id = data.data.userinfo.id;

                sessionStorage.setItem("appList", JSON.stringify(data.data.app))
                sessionStorage.setItem("user_multistage", data.data.userinfo.is_level == true ? true : false); /*保存用户多级身份 */
                sessionStorage.setItem("authority_url", JSON.stringify(data.data.personal))
                sessionStorage.setItem("parent_child_class_id", '')
                sessionStorage.setItem("parent_child_id", '')
                //默认跳转首页
                var redirectUrl = '/personal/index';
                if (!is_empty(sessionStorage.getItem('paramString'))) {
                    redirectUrl = sessionStorage.getItem('paramString');
                    sessionStorage.removeItem('paramString');
                }

                let classid = sessionStorage.getItem('classId')
                switch (decodeURIComponent(redirectUrl)) {

                    case 'circle': //班级圈
                        this.$router.push({ path: '/class/circle/index', query: { id: classid } })
                        break;
                    case 'notice': //班级通知
                        this.$router.push({ path: '/class/notice/index', query: { id: classid } })
                        break;
                    case 'achieve': //学生成绩
                        this.$router.push({ path: '/class/achieve/list', query: { id: classid } })
                        break;
                    case 'leave': //请假
                        this.$router.push({ path: '/class/leave/index', query: { id: classid } })
                        break;
                    case 'schedule': //班级课表
                        this.$router.push({ path: '/class/schedule/index', query: { id: classid } })
                        break;
                    case 'live_re': //教学直播
                        this.$router.push({ path: '/teach/live/listappoint' })
                        break;
                    case 'stuque': //我的提问
                        this.$router.push({ path: '/learn/ask/index' })
                        break;
                    case 'teaque': //我的问答
                        this.$router.push({ path: '/teach/ask/index' })
                        break;
                    case 'note': //学习笔记
                        this.$router.push({ path: '/learn/note/index' })
                        break;
                    case 'history': //学习足迹
                        this.$router.push({ path: '/learn/history/book' })
                        break;
                    case 'collect': //收藏
                        this.$router.push({ path: '/collect/openclass/index' })
                        break;
                    case 'contact': //通讯录
                        this.$router.push({ path: '/personal/contact/mailList' })
                        break;
                    case 'message': //消息
                        this.$router.push({ path: '/message/notice/index' })
                        break;
                    case 'archives': //消息
                        this.$router.push({ path: '/class/archives/index', query: { id: classid } })
                        break;
                    case 'homework': //作业 & 任务
                        this.$router.push({ path: '/class/homework/index', query: { id: classid } })
                        break;
                    default:
                        this.$router.push(decodeURIComponent(redirectUrl));
                }

                console.log('http://172.16.20.222:8081/personal/login?token=' +
                    sessionStorage.getItem('token') + '&host=' +
                    sessionStorage.getItem('host_addr').split('://')[1] +
                    '&CheckSchoolAppCode=' + sessionStorage.getItem('CheckSchoolAppCode'))
                // 

            });
            let fail = (data => {
                this.loading.txt = '验证失败...'
                this.$message.error(data.msg)
                //2后跳回首页
                setTimeout(() => {
                    window.location.href = sessionStorage.getItem('host_addr');
                }, 1000)
            });
            this.$ajax.get('api/login/new_login', { params: {}, func: { success: success, fail: fail } })
            // NProgress.done()
        },
        //过滤路由
        filterRoutes() {
            var this_route = [];
            console.log(routeConfig, 666,JSON.parse(JSON.stringify(this.routeData)))

            // for(let i = 0; i < routeConfig.length; i++){
            //     if(routeConfig[i].authName === this.routeData[i].name){
            //         // routeConfig[i].txtName = this.routeData[i].title
            //         for(let j = 0; j < routeConfig[i].children.length; j++){
            //             for(let k = 0; k < this.routeData[i].children.length; k++){
            //                  if(routeConfig[i].children[j].authName === this.routeData[i].children[k].name) {
            //                     routeConfig[i].children[j].txtName = this.routeData[i].children[k].title
            //                 }
            //             }
            //         }
            //     }
            // }

            routeConfig.forEach((v, i) => {

                var temp_route = {}
                //获取系统路由名字
                var sys_column = getOneColumn(this.routeData, 'name');
                var inx = sys_column.indexOf(v.authName);

                if (inx > -1 || v.authName === 'space') {
                    temp_route.path = v.path;
                    temp_route.name = v.name;
                    temp_route.authName = v.authName;
                    temp_route.txtName = v.txtName;
                    temp_route.hint = v.hint;
                    temp_route.component = v.component;
                    temp_route.template = v.template;
                    temp_route.children = [];
                    v.children.forEach((v1, i1) => {
                        if (v.authName == 'space') {
                            temp_route.children.push(v1);
                        } else if (!is_empty(this.routeData[inx].children)) {
                            //获取名字数组
                            var module_column = getOneColumn(this.routeData[inx].children, 'name');
                            if (module_column.indexOf(v1.authName) > -1) {
                                temp_route.children.push(v1)
                            }
                        }
                    })
                }

                if (Object.keys(temp_route).length > 0) {
                    this_route.push(temp_route)
                }
                // console.log(JSON.parse(JSON.stringify(this_route)), '88999')
            })

            sessionStorage.setItem("route_str", JSON.stringify(this_route))

            this.$router.options.routes[1].children = this_route;
            //生成动态路由
            this.$router.addRoutes(this.$router.options.routes)
            // console.log(this.$router.options.routes,' this.$router.options.routes ')
        },
        /**
         * 获取当前平台是教育局还是学校 1为学校 ，2为教育局
         * @DateTime 2020-08-11T15:40:53+0800
         * @qiu_m
         * @return   {[type]}                 [description]
         */
        getIsSchool() {
            let success = (res => {
                let data = res.data
                let level = data == 2 ? true : false
                this.$store.commit('SET_ISSCHOOL', level)
            });

            let params = {
                app_code: sessionStorage.getItem('CheckSchoolAppCode')
            }

            this.$ajax.get('api/newlevel/check_platform_server_type', { params, func: { success: success } })
        },
        // 获取当前平台是多级还是单机 （返回1为单机 返回2为多级
        getIsCheckLevel() {
            let success = res => {
                // console.log(res.data) // 值为返回值，返回1为单机 返回2为多级

                /*获取当前平台是 多级还是单机 1为单机 返回2为多级*/
                let data = res.data
                let level = data == 2 ? true : false
                console.log('SET_ISCHECKLEVEL: ',level);
                this.$store.commit('SET_ISCHECKLEVEL', level)
            }
            let params = {

            }

            this.$ajax.get('appapi/login/check_level_platform', { params, func: { success } })
        },
    }
}
</script>